/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:

    struct Compare {
        bool operator()(const Interval &a, const Interval &b) const {
            return a.start < b.start;
        }
    };

    vector<Interval> merge(vector<Interval> &intervals) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(intervals.begin(), intervals.end(), Compare());

        int n = intervals.size();
        int len = 0;
        for (int i = 0; i < n; ) {
            int j = i + 1;
            int start = intervals[i].start;
            int end = intervals[i].end;
            while (j < n && intervals[j].start <= end) {
                end = max(end, intervals[j].end);
                ++j;
            }
            intervals[len++] = Interval(start, end);
            i = j;
        }
        while (intervals.size() > len) {
            intervals.pop_back();
        }
        return intervals;
    }
};
